#include "sqlite.h"

/*对应注册功能的数据库操作函数*/
int register_new_user(sqlite3 *pdb,struct user_info *usr){
	int ret = 0;
	char sql[128]= ""; // 存储sql语句
	int rows = 0,cols = 0;
	char **presult;
	char *perrmsg = NULL;
	/*在用户信息表查找指定用户*/
	sprintf(sql,"SELECT * FROM user WHERE name ='%s'",usr->name);

	ret = my_sqlite3_get_table(pdb,sql,&presult,&rows,&cols,&perrmsg);
	if(ret != SQLITE_OK){
		sqlite3_free(perrmsg);
		perrmsg = NULL;
		pdb = NULL;
		return -1;
	}

	if(rows!= 0)    return 1;

	/*如果没找到 插入新记录*/
	if(rows == 0){
		sprintf(sql,"insert into user values('%s','%s',0)", usr->name,usr->passwd);
		ret = my_sqlite3_exec(pdb,sql,NULL,NULL,&perrmsg);
		if(ret != SQLITE_OK){
			printf("注册失败\n");
			sqlite3_free(perrmsg);
			perrmsg = NULL;
			sqlite3_close(pdb);
			pdb = NULL;
			return -2;
		}
	}
	return 0;
}

/*对应登录功能的数据库操作函数
将用户信息表中用户名为username记录的登录标记字段值为flag值*/
int user_login(sqlite3*pdb,struct user_info *usr){
    int ret = 0;
    char sql[128]= "";
    char **presult;
    int rows = 0,cols = 0;
	char *perrmsg = NULL;
    sprintf(sql,"SELECT name,password,flag FROM user WHERE name = '%s'", usr->name);

    ret = my_sqlite3_get_table(pdb,sql,&presult,&rows,&cols,&perrmsg);
    if(ret != SQLITE_OK){
	    sqlite3_free(perrmsg);
	    perrmsg = NULL;
	    sqlite3_close(pdb);
	    pdb = NULL;
	    return -1;
    }
    if(rows == 0){
	    sqlite3_free(perrmsg);
	    perrmsg = NULL;
    	sqlite3_close(pdb);
	    pdb = NULL;
	    return 1;
    }
    if(rows!=0){
	    if(strcmp(usr->passwd,*(presult+rows+cols))){
	        sqlite3_free_table(presult);
	        presult = NULL;
	        return 2;
	    }
	    if(strcmp(*(presult+rows+cols+1),"1")==0){
	        sqlite3_free(perrmsg);
	        perrmsg = NULL;
	        sqlite3_close(pdb);
	        pdb = NULL;
	        return 3;
	    }
	    if(strcmp(*(presult+rows+cols+1),"0")== 0 && strcmp(usr->passwd,*(presult+rows+cols))==0){ // 成功
	        sqlite3_free_table(presult);
	        presult = NULL;
	        update_login_flag(pdb,usr->name,1);
	        return 0;
	    }
    }
    return 0;
}

/*3. 对应用户的登出功能*/
int update_login_flag(sqlite3*pDB,char*username,int flag){
    int ret = 0;
    char sql[128]= "";
    sprintf(sql,"UPDATE user SET flag = %d WHERE name = '%s'",flag,username);
    char * perrmsg = NULL;
    ret = my_sqlite3_exec(pDB,sql,NULL,NULL,&perrmsg);
    if(ret != SQLITE_OK){
	    sqlite3_free(perrmsg);
	    perrmsg = NULL;
	    sqlite3_close(pDB);
	    pDB = NULL;
	    return 1;
    }
    return 0;
}